package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;


@Controller
@RequestMapping("/cargo/packing")
public class PackingController extends BaseController {
    @Reference
    private PackingService packingService;

    @Reference
    private ExportProductService exportProductService;

    @Reference
    private ContractService contractService;

    @Reference
    private ExportService exportService;

    /*
         url: /cargo/packing/checkPacking.do?id=di{}
         方法的作用：断该id的运单号是否符合装箱要求
         参数： id 运单的id
         返回： 运单结果  成功: 跳转toPacking方法  失败: 返回 带上错误信息
      */
    @RequestMapping(value = "/checkPacking", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String checkPacking(String[] id) {


        //创建mes字符串接收 结果信息
        String mes = "";

        //如果传入的参数为空
        if (id == null) {
            mes = "5";
            return mes;
        }

        //调用业务层判断该id的运单号是否符合装箱要求 1-4
        mes = exportService.checkPacking(id);

        return mes;
    }

    /*
    url: /cargo/packing/toPacking.do?id=di
    方法的作用：跳转到添加装箱页面 并回显信息
    参数： id 运单的id
    返回： 添加装箱页面
 */
    @RequestMapping("/toPacking")
    public String toPacking(String ids) {

        //分割运单id
        String[] idArray = ids.split(",");

        //存储合同号
        List<String> exportNoList = new ArrayList<>();

        //存储报运单ID集合
        List<String> exportIdList = new ArrayList<>();

        //存储总体积
        double totalVolume = 0;
        //存储总毛重
        double grossWeights = 0;

        //存储总净重
        double netWeights = 0;

        //查询所有的运单
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(Arrays.asList(idArray));
        List<Export> exportList = exportService.findAll(exportExample);


        //遍历报运单集合
        for (Export export : exportList) {
            //获取合同号
            exportNoList.add(export.getCustomerContract());

            //获取体积
            totalVolume += export.getMeasurements();

            //获取毛重
            Double grossWeight = export.getGrossWeights();
            grossWeights += grossWeight;

            //查询报运单中的商品
            ExportProductExample exportProductExample = new ExportProductExample();
            exportProductExample.createCriteria().andExportIdEqualTo(export.getId());
            List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);

            //遍历所有商品获取净重
            for (ExportProduct exportProduct : exportProductList) {

                Double netWeight = exportProduct.getNetWeight();
                if (netWeight!=null){
                    netWeights += netWeight;
                }
            }

            //获取报运单id
            exportIdList.add(export.getId());
        }

        //计算装箱费用  毛重*520
        double packingMoney = grossWeights * 520;

        //存储合同号 list --> string
        String exportNos = ArrayUtils.toString(exportNoList, ","); // 集合转字符串(逗号分隔,首尾加大括号) {0,1,2,3,4,5}

        //存储合同号 list --> string
        String exportIds = ArrayUtils.toString(exportIdList, ","); // 集合转字符串(逗号分隔,首尾加大括号) {0,1,2,3,4,5}


        request.setAttribute("exportNos", exportNos);
        request.setAttribute("totalVolume", totalVolume);
        request.setAttribute("grossWeights", grossWeights);
        request.setAttribute("netWeights", netWeights);
        request.setAttribute("packingMoney", packingMoney);
        request.setAttribute("exportIds", exportIds);


        return "cargo/export/export-toPacking";
    }

    /*
    url: /cargo/packing/addPacking.do?
    方法的作用：添加装箱单
    参数： 装箱单对象
    返回： 显示装箱单列表
   */
    @RequestMapping("/addPacking")
    public String addPacking(Incasement incasement) {

        packingService.save(incasement);

        //修改报运单的状态
        String exportIds = incasement.getExportIds().replace("[","").replace("]","");
        //分割运单id
        String[] idArray = exportIds.split(",");
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(Arrays.asList(idArray));
        List<Export> exportList = exportService.findAll(exportExample);

        //遍历报运单集合
        for (Export export : exportList) {
            //更新报运单状态
            export.setState(3);
            exportService.update(export);
        }


        return "redirect:/cargo/export/list.do";
    }



    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum,  @RequestParam(defaultValue = "5")int pageSize){
        PageInfo<Incasement> pageInfo=packingService.findByPage(pageNum,pageSize);
        request.setAttribute("pageInfo",pageInfo);
        System.out.println("pageInfo为"+pageInfo);
        return "cargo/incasement/incasement-list";
    }

    @RequestMapping("/delete")
    public String delete(String packingListId){
        packingService.deleteById(packingListId);
        return "redirect:/cargo/packing/list.do";

    }

    @RequestMapping("/toView")
    public String toView(String packingListId){
        Incasement incasement=new Incasement();
        incasement=packingService.findIncasementById(packingListId);
        request.setAttribute("incasement",incasement);
        return "cargo/incasement/view";
    }

    @RequestMapping("/toProxy")
    public String toProxy(String packingListId){
        Incasement incasement=packingService.findIncasementById(packingListId);
        String exportNos=incasement.getExportNos();
        exportNos=exportNos.replace("[","");
        exportNos=exportNos.replace("]","");
        String[] exportNo=exportNos.split(",");
        System.out.println("exportNOS为"+exportNo);
        Export export=exportService.findByNo(exportNo[0]);
        System.out.println("查询结果为"+export);
        request.setAttribute("export",export);
        request.setAttribute("packingListId",packingListId);

        return "cargo/incasement/toProxy";
    }

    @RequestMapping("/save")
    public String save(IncasementProxy incasementProxy){
        System.out.println("incasementProxy的值为"+incasementProxy);
        Incasement incasement=packingService.findIncasementById(incasementProxy.getShippindOrderId());
        incasementProxy.setLoadingDate(incasement.getPackingTime1());
        incasementProxy.setCreateBy(getLoginUser().getUserName());
        incasementProxy.setCreateDept(getLoginUser().getDeptName());
        incasementProxy.setCreateTime(new Date());

        packingService.insertSelective(incasementProxy);
        incasement.setState(1);
        packingService.updateIncasement(incasement);
        return "redirect:/cargo/packing/list.do";
    }

    @RequestMapping("/toJudgement")
    @ResponseBody
    public Map<String,Object> toJudgement(String packingListId){
        Map<String,Object> resultMap = new HashMap<>();
        boolean flag =  packingService.findState(packingListId);
        if(flag==false){
            resultMap.put("message","该运单已生成委托书");
        }
        //删除失败
        resultMap.put("flag",flag);
        resultMap.put("packingListId",packingListId);
        return resultMap;
    }
}
